package lib

import (
	"RMS/app/shop/model"
	"RMS/common"
	"RMS/common/db"
	"context"
	"gorm.io/gorm"
	"log"
)

func ImplItemList(ctx context.Context, req *model.ItemListReq) *model.ItemListResp {
	resp := &model.ItemListResp{}

	d := db.NewRmsDBRequest(ctx)
	d = d.Table(db.PmsItemTable)
	d.Select("pms_item.*,pms_category.name category_name")
	itemListfilter(ctx, req, d)

	d.Joins("left join pms_category on pms_category.id = pms_item.category_id")

	var total int64
	d.Count(&total)

	if req.PageSize != nil && req.PageIndex != nil {
		d.Offset((*req.PageIndex - 1) * *req.PageSize).Limit(*req.PageSize)
	}

	var data []map[string]interface{}
	if err := d.Find(&data).Error; err != nil && err != gorm.ErrRecordNotFound {
		log.Printf("ItemList err := %v\n", err.Error())
		resp.Status = common.ErrCode
		resp.Message = common.FindErrMessage
		return resp
	}
	log.Println(data)

	resp.Status = common.SuccessCode
	resp.Message = common.SuccessMessage
	resp.Data = data
	resp.Total = int(total)
	return resp
}
func itemListfilter(ctx context.Context, req *model.ItemListReq, d *gorm.DB) {
	if req.Id != nil {
		d.Where("id = ?", *req.Id)
	}
	if req.Name != nil {
		d.Where("pms_item.name like ?", *req.Name+"%")
	}
	if req.CategoryId != nil {
		d.Where("category_id = ?", *req.CategoryId)
	}
}
